<template>
<div id="">
  <el-form ref="mooc" :model="formData" class="full-width-input content" :rules="rules" label-width="108px" :size="defaultFormItemSize" :disabled="formStatus  == 'show' ? true : false">
    <el-row :gutter="20" style="display: flex; flex-wrap: wrap">
      <el-col :span="24">
        <el-form-item label="标题" prop="title" :rules="$commonRules({ rule: 'required', msg: '请输入标题'})">
          <el-input class="input-item" v-model="formData.title" :clearable="true" placeholder="请输入标题" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所属栏目" prop="infoItem" :rules="$commonRules({ rule: 'required', msg: '请选择所属栏目', trigger:'change' })">
          <el-select class="input-item" v-model="formData.infoItem" :clearable="true" filterable placeholder="请选择所属栏目">
            <el-option v-for="item in initData.infoItem.dropdownList" :key="item.id" :value="item.id" :label="item.name" :disabled="item.disabled">
              <el-row type="flex" justify="space-between" align="middle">
                <span>{{item.name}}</span>
                <el-tag v-if="item.disabled" size="mini" type="info" style="margin-left: 20px;">已禁用</el-tag>
              </el-row>
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="来源" prop="infoSource">
          <el-input class="input-item" v-model="formData.infoSource" :clearable="true" placeholder="请输入来源" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="发布时间" prop="publishTime" :rules="$commonRules({ rule: 'required', msg: '请选择发布时间', trigger:'change' })">
          <el-date-picker v-model="formData.publishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="是否幻灯片" prop="isHeadline" :rules="$commonRules({ rule: 'required', msg: '请选择是否幻灯片', trigger:'change' })">
          <el-radio v-model="formData.isHeadline" label="1">是</el-radio>
          <el-radio v-model="formData.isHeadline" label="0">否</el-radio>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="封面图片" prop="coverImage">
          <el-upload class="upload-image-item upload-image-multi" name="uploadFile" :headers="getUploadHeaders" :action="getUploadActionUrl('/admin/upms/file/upload')" :data="{ asImage: true}" multiple :on-success="onPictureUrlUploadSuccess"
            :on-remove="onPictureUrlRemoveFile" :before-upload="pictureFile" list-type="picture-card" :file-list="uploadWidgetImpl.fileList" :show-file-list="true" :on-preview="handlePreview">
            <i class="el-icon-plus upload-image-item"></i>
            <div slot="tip" class="el-upload__tip" style="textAlign:left">请上传清晰度较高的图片</div>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="视频">
          <el-radio v-model="formData.isUrl" label="1" @change="isUrlChange()">上传视频</el-radio>
          <el-radio v-model="formData.isUrl" label="0" @change="isUrlChange()">保存链接</el-radio>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="formData.isUrl == '1'">
        <el-form-item prop="videoUrl">
          <upload-video :videos="videoList" @delete="deleteVideo" @change="getVideo" :formStatus="formStatus">
          </upload-video>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="formData.isUrl == '0'">
        <el-form-item>
          <el-input placeholder="请输入视频地址" v-model="formData.videoUrl">
            <template slot="append">
              <el-button @click="showVideo" class="btn">预览</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="正文" prop="content">
          <rich-editor-new :value.sync="formData.content" :readOnly="formStatus == 'show'"></rich-editor-new>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-dialog :visible.sync="dialogVisible" append-to-body center title="视频查看">
    <video :src="videoSrc" ref="video" controls alt style="width: 800px; height: 600px">您的浏览器不支持视频播放</video>
  </el-dialog>
</div>
</template>
<script>
import {
  UploadWidget
} from '@/utils/widget.js';
import {
  uploadMixin
} from '@/core/mixins';
import projectConfig from '@/core/config';
import {
  api as viewerApi
} from 'v-viewer';
import {
  SystemController
} from '@/api';
export default {
  name: "",
  mixins: [uploadMixin],
  props: {
    initData: {
      type: Object,
      default: () => {
        return {
          infoItem: {},
          infoSource: {},
        }
      }
    },
    formStatus: {
      tyoe: String,
      default: "add"
    },
    initForm: {
      tyoe: Object,
      default: {}
    }
  },
  data() {
    return {
      formData: {},
      rules: {},
      areaProps: {
        value: 'code',
        label: 'name'
      },
      uploadWidgetImpl: new UploadWidget(10),
      dialogVisible: false,
      dialogImageUrl: "",
      videoList: [],
      dialogVisible: false,
      videoSrc: ""
    }
  },
  mounted() {
    if (Object.values(this.initForm).length > 0) {
      this.initFormContent()
    }
  },
  methods: {
    initFormContent() {
      let me = this;
      me.$set(me, "formData", me.initForm);
      if (me.formData?.coverImage?.length > 0) {
        let arr = [];
        me.formData.coverImage.forEach((item, i) => {
          me.uploadWidgetImpl.fileList.push({
            filename: item,
            url: projectConfig.baseUrl + 'admin/upms/file/download?filename=' + item
          })
        });
      };
      if (me.formData.videoUrl) {
        if (me.formData.videoUrl.indexOf('http') == -1) {
          me.videoList = [{
            videoLink: me.formData.videoUrl
          }];
          me.$set(me.formData, "isUrl", '1')
        } else {
          me.videoList = [];
          me.$set(me.formData, "isUrl", '0')
        }
      } else {
        me.$set(me.formData, "isUrl", '1')
      }

    },
    getFormData() {
      let flag = true;
      this.$refs.mooc.validate((valid) => {
        flag = valid ? true : false
      })
      return flag ? this.formData : {}
    },
    onPictureUrlUploadSuccess(response, file, fileList) {
      if (response.success) {
        file.downloadUri = response.data.downloadUri;
        file.filename = response.data.filename;
        file.url = URL.createObjectURL(file.raw);
        this.uploadWidgetImpl.onFileChange(file, fileList);
        this.formData.coverImage = this.uploadWidgetImpl.fileList.map(x => x.filename)
        this.fileListToJson(this.uploadWidgetImpl.fileList);
      } else {
        this.$message.error(response.message);
      }
    },
    /**
     * 移除课程图片
     */
    onPictureUrlRemoveFile(file, fileList) {
      this.uploadWidgetImpl.onFileChange(file, fileList);
      this.formData.coverImage = this.uploadWidgetImpl.fileList.map(x => x.filename)
    },
    handlePreview(val) {
      let arr = this.formData.coverImage.map(x => {
        return projectConfig.baseUrl + 'admin/upms/file/download?filename=' + x + '&type=1'
      });
      const $viewer = viewerApi({
        images: arr
      })
    },
    deleteVideo(index) {
      this.formData.videoUrl = "";
      this.videoList.splice(index, 1)
    },
    getVideo(event) {
      let me = this;
      let fm = new FormData();
      fm.append('uploadFile', event[0].videoFile.raw)
      fm.append('asImage', false)
      if (event.length > 0) {
        SystemController.uploadFiles(me, fm, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
        }).then(res => {
          me.formData.videoUrl = res.data.filename;
          me.videoList = [{
            videoLink: me.formData.videoUrl
          }]
        }).catch(err => {
          me.$message.error('上传失败，请稍后重试')
        })
      }
    },
    isUrlChange(val) {
      this.$set(this.formData, "videoUrl", "")
      if (val == '1') {
        this.videoList = []
      }
    },
    showVideo() {
      let me = this;
      if (me.formData.videoUrl) {
        me.videoSrc = me.formData.videoUrl;
        me.dialogVisible = true
      } else {
        me.$message.warning('请输入视频地址')
      }
    },

  }
}
</script>
<style lang="scss" scoped>
</style>
